package com.lagou.edu.service.impl;

import com.lagou.edu.annotation.Autowired;
import com.lagou.edu.annotation.Service;
import com.lagou.edu.annotation.Transactional;
import com.lagou.edu.dao.AccountDao;
import com.lagou.edu.dao.impl.JdbcAccountDaoImpl;
//import com.lagou.edu.factory.BeanFactory;
import com.lagou.edu.pojo.Account;
import com.lagou.edu.service.TransferService;
import com.lagou.edu.utils.ConnectionUtils;
import com.lagou.edu.utils.TransactionManager;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//import com.lagou.edu.utils.ConnectionUtils;
//import com.lagou.edu.utils.TransactionManager;

/**
 * @author 应癫
 */
@Service("transferService")
@Transactional("transferService")
public class TransferServiceImpl implements TransferService {
//private AccountDao accountDao = new JdbcAccountDaoImpl();

    // private AccountDao accountDao = (AccountDao) BeanFactory.getBean("accountDao");

    // 最佳状态
    @Autowired
    private AccountDao accountDao;

//    // 构造函数传值/set方法传值
//    public void setAccountDao(AccountDao accountDao) {
//        this.accountDao = accountDao;
//    }

    @Override
    public void transfer(String fromCardNo, String toCardNo, int money) throws Exception {

//        try{
//            // 开启事务(关闭事务的自动提交)
//            TransactionManager.getInstance().beginTransaction();
//        ConnectionUtils.getInstance().getCurrentThreadConnection().setAutoCommit(false);//关闭自动提交
        Account from = accountDao.queryAccountByCardNo(fromCardNo);
        Account to = accountDao.queryAccountByCardNo(toCardNo);


        from.setMoney(from.getMoney()-money);
        to.setMoney(to.getMoney()+money);

        accountDao.updateAccountByCardNo(to);
        int i = 1/0;
        accountDao.updateAccountByCardNo(from);

            // 提交事务
//        ConnectionUtils.getInstance().getCurrentThreadConnection().commit();
//            TransactionManager.getInstance().commit();
//        }catch (Exception e) {
//            e.printStackTrace();
//            // 回滚事务
////            ConnectionUtils.getInstance().getCurrentThreadConnection().rollback();
//            TransactionManager.getInstance().rollback();
//
//            // 抛出异常便于上层servlet捕获
//            throw e;
//
//        }




    }
}
